package org.example.mqtexxt.mqserver.datacenter;

import org.apache.ibatis.annotations.Mapper;
import org.example.mqtexxt.MqTexxtApplication;
import org.example.mqtexxt.mqserver.core.Binding;
import org.example.mqtexxt.mqserver.core.Exchange;
import org.example.mqtexxt.mqserver.core.ExchangeType;
import org.example.mqtexxt.mqserver.core.MSGQueue;
import org.example.mqtexxt.mqserver.mapper.MetaMapper;

import java.io.File;
import java.util.List;

/*
通过这个类来整合数据库的增删改查的基础操作
 */

public class DataBaseMapper {

    private MetaMapper metaMapper;

    //编写一个初始化方法
    public void init(){
        metaMapper = MqTexxtApplication.context.getBean(MetaMapper.class);
        if(!checkDBExists()){
            //先去创建一个data目录
            File dataDir = new File("./data");
            dataDir.mkdir();
            createTable();
            createDefalutData();
            System.out.println("[DataBaseMapper] 数据库初始化完成了");
        }else{
            System.out.println("[DataBaseMapper] 数据库已经存在了");
        }
    }

    //判断数据库是否存在
    public boolean checkDBExists(){
        File file = new File("./data/meta.db");
        if(file.exists()){
            return true;
        }
        return false;
    }

    //创建数据库和表
    private  void createTable(){
        metaMapper.createExchangeTable();
        metaMapper.createQueueTable();
        metaMapper.createBindingTable();
        System.out.println("[DataBaseMapper] 创建表完成了");
    }

    //这个方法用来添加默认数据，一个默认交换机
    private void createDefalutData(){
        Exchange exchange = new Exchange();
        exchange.setName("");
        exchange.setType(ExchangeType.DIRECT);
        exchange.setDurable(true);
        exchange.setAutoDelete(false);
        metaMapper.insertExchange(exchange);
        System.out.println("[DataBaseMapper] 创建初始化数据(一个默认交换机)完成了");
    }

    public void insertExchange(Exchange exchange){
        metaMapper.insertExchange(exchange);
    }
    public void deleteExchange(String exchangeName){
        metaMapper.deleteExchange(exchangeName);
    }
    public void insertQueue(MSGQueue queue){
        metaMapper.insertQueue(queue);
    }
    public void deleteQueue(String queueName){
        metaMapper.deleteQueue(queueName);
    }
    public void insertBinding(Binding binding){
        metaMapper.insertBinding(binding);
    }
    public void deleteBinding(Binding binding){
        metaMapper.deleteBinding(binding);
    }

    public List<Exchange> selectAllexchanges(){
        return metaMapper.selectAllExchanges();
    }

    public List<MSGQueue> selectAllQueues(){
        return metaMapper.selectAllQueues();
    }

    public List<Binding> selectAllBindings(){
        return metaMapper.selectAllBindings();
    }

    public void deleteDB(){
        File file = new File("./data/meta.db");
        boolean ret  = file.delete();
        if(ret == true){
            System.out.println("[DataBaseMapper] 删除数据库成功");
        }else{
            System.out.println("[DataBaseMapper] 删除数据库失败");
        }
    }



}
